package com.ssy.lingxi.report.handler.notify;

import cn.hutool.json.JSONUtil;
import com.rabbitmq.client.Channel;
import com.ssy.lingxi.report.api.constant.ReportConstants;
import com.ssy.lingxi.report.api.vo.request.OperateNoticeAddVO;
import com.ssy.lingxi.report.service.IMemberHomeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 *  系统操作通知
 * @author ds
 * @date 2021/6/1
 * @version 2.0.0
 */
@Component
public class SysOperateNoticeMessageHandler {

    @Autowired
    private IMemberHomeService memberHomeService;

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @RabbitListener(queues = ReportConstants.REPORT_SYS_OPERATE_NOTICE_QUEUE,ackMode ="MANUAL")
    public void handler(Message message, Channel channel) throws IOException {
        try {
            OperateNoticeAddVO request=JSONUtil.toBean(new String(message.getBody()), OperateNoticeAddVO.class);
            memberHomeService.addOperateNotice(request);
            //确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch(DataIntegrityViolationException e){//唯一约束冲突异常
            log.info("[系统操作通知]重复消费通知,body:{}",new String(message.getBody()));
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            log.error("处理[系统操作通知]异常,body:{},异常消息：",new String(message.getBody()),e);
            channel.basicRecover(false);
        }

    }
}
